using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;

using System.Xml;

namespace Pampa.WebControls
{
    public enum ComboListType
    {
        BasicCombo = 2, EditableCombo = 3
    }

    [ToolboxData("<{0}:ComboList runat=server></{0}:ComboList>")]
    [DesignerAttribute(typeof(BaseDesigner), typeof(System.ComponentModel.Design.IDesigner))]
    public class ComboList : BaseControl
    {
        ListItemCollection items;
        ComboListType type = ComboListType.BasicCombo;

        string aValue;
        string aText;

        string pathImages = "Pampa.WebControls" + GetImagesPath();
        int size = 5;
        string onClientChange;

        public ComboList()
        {
            this.items = new ListItemCollection();
            this.Width = Unit.Pixel(100);

            this.CssClass = "comboListDefault";
            this.clientClass = "WebComboList";
        }

        #region Load

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // registro el estilo y las librerias javascript en la pagina
            if (this.CssClass == "comboListDefault")
                RegisterStyleSheet("Pampa.WebControls/ComboList.css");

            // DEBUG
            #if WEBCONTROL_DEBUG
                RegisterStyleSheet("Pampa.WebControls/FloatingWindow.css");

                RegisterLibrary("Pampa.WebControls/Drag.js");
                RegisterLibrary("Pampa.WebControls/FloatingWindow.js");
                RegisterLibrary("Pampa.WebControls/AlertWindow.js");
                RegisterLibrary("Pampa.Common/Debug.js");

                RegisterLibrary("Js/_FocusManager.js");
                RegisterLibrary("Js/_ComboList.js");
            #else
                RegisterLibrary("Pampa.Common/Common.js");
                RegisterLibrary("Pampa.WebControls/FocusManager.js");
                RegisterLibrary("Pampa.WebControls/ComboList.js");
            #endif

            // recupero los items y el valor tomado en el cliente
            if (Page.IsPostBack)
            {
                LoadStruct();
                LoadValue();
            }
        }

        #endregion

        #region Public Functions

        /// <summary>
        /// Esta funcion permite cargar el combo con una lista de tuplas clave-valor.
        /// </summary>
        /// <param name="list"></param>
        public void LoadList(IList<KeyValuePair<string, string>> list)
        {
            this.items.Clear();

            foreach (KeyValuePair<string, string> item in list)
            {
                this.items.Add(new ListItem(item.Value, item.Key));
            }
        }

        #endregion

        #region Properties

        public ListItemCollection Items
        {
            get
            {
                return items;
            }
        }

        public ComboListType Type
        {
            get { return type; }
            set { type = value; }
        }

        public int Size
        {
            get { return size; }
            set { size = value; }
        }

        public string Value
        {
            get { return aValue; }
            set { aValue = value; }
        }

        /// <summary>
        /// Path desde donde se cargaran las imagenes
        /// </summary>
        public string PathImages
        {
            get{ return pathImages; }
            set{ pathImages = value; }
        }

        public string OnClientChange
        {
            get { return onClientChange; }
            set { onClientChange = value; }
        }

        protected string ObjectName
        {
            get { return "lst" + this.ID.Replace(".", "_"); }
        }
            
        #endregion

        #region Render

        protected override void Render(HtmlTextWriter writer)
        {
            writer.AddAttribute("id", "cont_" + this.ID);
            writer.AddAttribute("class", this.CssClass);
            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            writer.RenderEndTag();

            RenderDefinitions(writer);
        }

        /// <summary>
        /// Construyo el objeto cliente que representa al combo
        /// </summary>
        private void RenderDefinitions(HtmlTextWriter output)
        {
            string objectName = this.ObjectName;

            output.WriteLine("<script type=\"text/javascript\">");
            output.WriteLine("var " + objectName + " = new " + this.clientClass + "(\"" + this.ID + "\", " + ((int)this.Type).ToString() + ");");

            // Properties                
            RenderProperties(output);
            
            // Show
            output.WriteLine(objectName + ".Show(\"cont_" + this.ID + "\",\"" + GetResourceUrl(this.PathImages) + "\");");
            output.WriteLine("</script>");
        }

        protected virtual void RenderProperties(HtmlTextWriter output)
        {
            string objectName = this.ObjectName;

            // Properties
            output.WriteLine(objectName + ".size = " + this.Size + ";");
            output.WriteLine(objectName + ".width = " + this.Width.Value + ";");
            output.WriteLine(objectName + ".text = \"" + this.aText + "\";");
            output.WriteLine(objectName + ".enabled = " + this.Enabled.ToString().ToLower() + ";");
            output.WriteLine(objectName + ".cssClass = \"" + this.CssClass + "\";");
            output.WriteLine(objectName + ".onChange = \"" + this.onClientChange + "\";");

            // Items
            foreach (ListItem item in this.Items)
            {
                string value = item.Value.Replace("\"", "\\\"");
                string text = item.Text.Replace("\"", "\\\"");

                output.WriteLine(objectName + ".AddItem(\"" + value + "\", \"" + text + "\");");
            } 

            output.WriteLine(objectName + ".SelectItem('" + this.Value + "', true);");
        }
        
        #endregion

        #region Recover Client Data

        private void LoadStruct()
        {
            string strValues = Page.Request[this.ID + "_values"];
            string strCaptions = Page.Request[this.ID + "_captions"];

            string[] values = strValues.Split('|');
            string[] captions = strCaptions.Split('|');

            this.Items.Clear();

            ListItem item;
            for (int i = 0; i < values.Length; i++)
            {
                item = new ListItem(captions[i], values[i]);
                this.Items.Add(item);
            }
        }

        private void LoadValue()
        {
            aValue = Page.Request[this.ID];
            aText = Page.Request["selec" + this.ID];
        }

        #endregion
    }
}